import React from 'react';
import { Upload, Icon, message } from 'antd';

function beforeUpload(file) {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/gif';
    if (!isImage) {
        message.error('上传的文件必须为图片!');
    }
    const isLtMB = file.size / 1024 / 1024 < 10;
    if (!isLtMB) {
        message.error('上传的图片不能大于 10MB!');
    }
    return isImage && isLtMB;
}

/**
 * 图片上传组件
 * 
 * 使用方式 <ImageUpload name={'imageId'} />;
 */
class ImageUpload extends React.Component {
    state = {
        loading: false,
        imageUrl: '',
        type: 'A'
    };

    constructor(props) {
        super(props);

        if (this.props.value) {
            this.state = {
                imageUrl: this.getImageUrl(this.props.value),
            };
        }
    }

    componentWillReceiveProps(nextProps) {
        if ('value' in nextProps) {
            const value = nextProps.value;
            this.setState({
                imageId: value
            });
        }
    }

    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        } else if (info.file.status === 'done') {
            //上传失败
            if (info.file.response.code != '0000') {
                this.setState({
                    loading: false
                });
                message.error(info.file.response.msg);
                return;
            }

            //上传成功
            this.setState({
                imageUrl: this.getImageUrl(info.file.response.id),
                loading: false
            });

            this.triggerChange(info.file.response.id);

        }
    }

    triggerChange(value) {
        const onChange = this.props.onChange;
        if (onChange) {
            onChange(value);
        }
    }

    getImageUrl(id) {
        return `/api/file/get?type=${this.state.type}&id=${id}`;
    }

    render() {
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传</div>
            </div>
        );
        const imageUrl = this.state.imageUrl;
        return (
            <Upload
                name="f"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="/api/file/upload.json?type=A"
                beforeUpload={beforeUpload}
                onChange={this.handleChange}
            >
                {imageUrl ? <img style={{ width: "128px", height: "128px" }} src={imageUrl} alt="" /> : uploadButton}
            </Upload>
        );
    }
}


export { ImageUpload };